﻿using System.Collections.Generic;
using System.Data.SQLite;
using SimpleOrmCFPC.upgrade;

namespace SimpleOrmCFPC.engines.sqlite
{
    internal class SQLiteTableDialect : TableDialect
    {
        private SQLiteConnection connection;

        public SQLiteTableDialect(SQLiteConnection connection)
        {
            this.connection = connection;
        }

        public string GenerateCreateTableRequest(string tableName, List<ColumnInfo> columns)
        {
            string request = "create table " + tableName + " (";
            var fields = new List<string>();
            foreach (ColumnInfo columnInfo in columns)
            {
                string decl = columnInfo.Name + " " + ConvertType(columnInfo.Type, columnInfo.MaxLength) + " ";

                if (columnInfo.PrimaryKey)
                {
                    decl += "primary key ";
                }
                if (columnInfo.AutoIncrement)
                {
                    decl += "autoincrement ";
                }
                if (columnInfo.NotNull)
                {
                    decl += "not null ";
                }
                fields.Add(decl);
            }

            string decls = string.Join(", ", fields.ToArray());
            request += decls + ")";
            return request;
        }

        public string ConvertType(DbType dbType, int length)
        {
            var maps = new Dictionary<DbType, string>
                           {
                               {DbType.Integer, "integer"},
                               {DbType.Float, "float"},
                               {DbType.Date, "datetime"},
                               {DbType.Char, "varchar"},
                               {DbType.Bigint, "bigint"}
                           };
            var sqlType = maps[dbType];
            if (dbType == DbType.Char)
            {
                sqlType += "(" + length + ") ";
            }

            return sqlType;
        }
    }
}